// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

library analyzer.parser;

import 'package:async/async.dart';
import 'package:snooperlang/snooperlang.dart';

import 'dart:io';

import 'package:lpg2/lpg2.dart';
import 'package:snooperlang/src/AstDumper.dart';
import 'package:snooperlang/src/SnooperLexer.dart';


import 'package:snooperlang/src/snooperParser.dart';
import 'package:snooperlang/src/snooperParsersym.dart';
import 'package:analyzer/src/dart/ast/ast.dart';
import 'package:analyzer/src/generated/source.dart';
export 'package:analyzer/src/dart/error/syntactic_errors.dart';

/// A parser used to parse tokens into an AST structure.
class Parser {

  bool isNumber(String str) {
    int length = str.length;
    for (int i = 0; i < length; i += 1) {
      switch(str[i]){
        case 'a':
        case 'A':
        case 'b':
        case 'B':
        case 'c':
        case 'C':
        case 'd':
        case 'D':
        case 'e':
        case 'E':
        case 'f':
        case 'F':
        case '0':
        case '1':
        case '2':
        case '3':
        case '4':
        case '5':
        case '6':
        case '7':
        case '8':
        case '9':
          break;
        default:
          return false;
      }
    }
    return true;

  }
  CompilationUnitImpl parseCompilationUnit(Source source) {

    var inputChars=source.contents.data;
    inputChars += "\n";
    var lexer = snooperLexer(source.fullName, 4, inputChars); // Create the lexer
    var parser = snooperParser(lexer.getILexStream()); // Create the parser
    lexer.lexer(parser.getIPrsStream());
    var tokens = parser.prsStream.tokens;
    for (var i = 0; i < tokens.size()-1; ++i)
    {
      Token token = tokens.get(i);
      var s = token.toString();
      var kind = token.getKind();
      if(kind == snooperParsersym.TK_IDENTIFIER){

        if(!isNumber(s)) {
          continue;
        }
        Token tokenNext = tokens.get(i+1);
        kind = tokenNext.getKind();
        if( kind == snooperParsersym.TK_LPAREN || kind == snooperParsersym.TK_EQUAL) {
          continue;
        }
        token.setKind(snooperParsersym.TK_NUMBER);
      }
    }
    var lineInfo = LineInfo.fromContent(inputChars);

    var ast = parser.parser();
    late CompilationUnitImpl  unit ;
    if(ast != null){
      var  node = ast as SnooperProg;
      unit = CompilationUnitImpl(node);
    }
    else{
      unit = CompilationUnitImpl(null);
    }
    unit.lineInfo = lineInfo;
    return unit;
  }
}
